<template>
  <el-card class="category-selector">
    <el-form inline class="category-selector-form">
      <el-form-item label="一级分类">
        <el-select
          placeholder="请选择分类"
          :value="category1Id"
          :disabled="disabled"
          @change="getCategory2List"
        >
          <!--
            value 是select收集的数据
            label 展示的内容
           -->
          <el-option
            v-for="c1 in category1List"
            :key="c1.id"
            :label="c1.name"
            :value="c1.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="二级分类">
        <el-select
          placeholder="请选择分类"
          :value="category2Id"
          :disabled="disabled"
          @change="getCategory3List"
        >
          <el-option
            v-for="c2 in category2List"
            :key="c2.id"
            :label="c2.name"
            :value="c2.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="三级分类">
        <el-select
          placeholder="请选择分类"
          :value="category3Id"
          :disabled="disabled"
          @change="setCategory3Id"
        >
          <el-option
            v-for="c3 in category3List"
            :key="c3.id"
            :label="c3.name"
            :value="c3.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { mapState, mapActions, mapMutations } from 'vuex'

export default {
  name: 'CategorySelector',
  props: {
    disabled: {
      type: Boolean,
      required: true
    }
  },
  computed: {
    ...mapState({
      // 选中的分类id
      category1Id: (state) => state.category.category1Id,
      category2Id: (state) => state.category.category2Id,
      category3Id: (state) => state.category.category3Id,
      // 展示的分类列表
      category1List: (state) => state.category.category1List,
      category2List: (state) => state.category.category2List,
      category3List: (state) => state.category.category3List
    })
  },
  methods: {
    ...mapActions([
      'category/getCategory1List',
      'category/getCategory2List',
      'category/getCategory3List'
    ]),
    ...mapMutations(['category/SET_CATEGORY3_ID', 'category/RESET_CATEGORY']),
    getCategory2List(category1Id) {
      this['category/getCategory2List'](category1Id)
    },
    getCategory3List(category2Id) {
      this['category/getCategory3List'](category2Id)
    },
    setCategory3Id(category3Id) {
      this['category/SET_CATEGORY3_ID'](category3Id)
    }
  },
  mounted() {
    this['category/getCategory1List']()
  },
  beforeDestroy() {
    // 清空所有id和所有list
    this['category/RESET_CATEGORY']()
  }
}
</script>

<style lang="sass" scoped>
.category-selector
  margin: 10px
.category-selector-form
  margin: 10px 0 -5px
</style>
